package com.example.vaccine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.vaccine.VO.PageVO;
import com.example.vaccine.VO.RecordVO;
import com.example.vaccine.VO.ResultVO;
import com.example.vaccine.entity.CheckTasks;
import com.example.vaccine.entity.Vaccines;
import com.example.vaccine.mapper.CheckTasksMapper;
import com.example.vaccine.mapper.VaccinesMapper;
import com.example.vaccine.service.CheckTasksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vaccine.util.CommonUtil;
import com.example.vaccine.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Coisn
 * @since 2025-06-12
 */
@Service
public class CheckTasksServiceImpl extends ServiceImpl<CheckTasksMapper, CheckTasks> implements CheckTasksService {

    @Autowired
    private VaccinesMapper vaccinesMapper;

    @Override
    public ResultVO getPaginatedTasks(int page, int pageSize) {
        Page<CheckTasks> taskPage = new Page<>(page, pageSize);
        IPage<CheckTasks> resultPage = this.page(taskPage);

        PageVO pageVO = new PageVO();
        pageVO.setData(resultPage.getRecords()); // 当前页数据
        pageVO.setTotal(resultPage.getTotal());  // 总条数

        return ResultVOUtil.success(pageVO);
    }

    @Override
    public Map<String, Integer> getStatusCounts() {
        List<CheckTasks> allTasks = this.list();
        return allTasks.stream().collect(Collectors.groupingBy(CheckTasks::getStatus, Collectors.summingInt(e -> 1)));
    }

    /**
     * 获取未分配疫苗分页列表（没有处于assigned/in_progress状态的任务）
     */
    @Override
    public PageVO getUnassignedVaccines(Integer page, Integer size) {
        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;

        // 查询所有处于assigned或in_progress状态的疫苗编号
        List<String> assignedVaccineNumberings = this.baseMapper.selectAssignedVaccineNumberings();

        Page<Vaccines> pageInfo = new Page<>(page, size);
        QueryWrapper<Vaccines> wrapper = new QueryWrapper<>();
        if (!assignedVaccineNumberings.isEmpty()) {
            wrapper.notIn("numbering", assignedVaccineNumberings);
        }

        Page<Vaccines> vaccinePage = vaccinesMapper.selectPage(pageInfo, wrapper);

        List<RecordVO> voList = vaccinePage.getRecords().stream().map(v -> {
            RecordVO vo = new RecordVO();
            vo.setId(v.getId());
            vo.setName(v.getName());
            vo.setNumbering(v.getNumbering());
            vo.setProductionDate(v.getProductionDate());
            vo.setFlag(v.getFlag());
            return vo;
        }).collect(Collectors.toList());

        PageVO pageVO = new PageVO();
        pageVO.setData(voList);
        pageVO.setTotal(vaccinePage.getTotal());
        return pageVO;
    }

    /**
     * 批量分配疫苗给核查员
     */
    @Transactional
    @Override
    public boolean  assignVaccinesToChecker(Integer checkerId, List<String> vaccineNumberings) {
        if (checkerId == null || vaccineNumberings == null || vaccineNumberings.isEmpty()) {
            return false;
        }

        // 构造批量插入任务
        List<CheckTasks> tasks = vaccineNumberings.stream().map(numbering -> {
            CheckTasks task = new CheckTasks();
            task.setCheckerId(checkerId);
            task.setVaccineNumbering(numbering);
            task.setAssignedAt(new Date());
            task.setStatus("in_progress");
            return task;
        }).collect(Collectors.toList());

        return this.saveBatch(tasks);
    }
}

